<template>
  <div class="animated-number">
    <span
      v-for="(digit, idx) in digits"
      :key="idx + '-' + digit"
      class="digit"
      :class="{ animate: animatingIndices.has(idx) }"
      @animationend="onAnimationEnd(idx)"
    >
      {{ displayDigits[idx] }}
    </span>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  number: {
    type: [Number, String],
    required: true,
  },
})

const digits = ref(String(props.number).split(''))
const displayDigits = ref([...digits.value])
const animatingIndices = ref(new Set())

watch(
  () => props.number,
  (newVal) => {
    const newDigits = String(newVal).split('')
    newDigits.forEach((digit, idx) => {
      if (displayDigits.value[idx] !== digit) {
        animatingIndices.value.add(idx)
      }
    })
    digits.value = newDigits
  }
)

function onAnimationEnd(idx) {
  displayDigits.value[idx] = digits.value[idx]
  animatingIndices.value.delete(idx)
}
</script>

<style scoped>
.animated-number {
  display: flex;
  gap: 0.1em;
}

.digit {
  display: inline-block;
  /* 你可以在这里控制字体大小、颜色 */
}

@keyframes floatUpDisappear {
  0% {
    transform: translateY(0);
    opacity: 1;
  }
  70% {
    transform: translateY(-20px);
    opacity: 0;
  }
  100% {
    transform: translateY(-20px);
    opacity: 0;
  }
}

@keyframes floatUpAppear {
  0% {
    transform: translateY(20px);
    opacity: 0;
  }
  100% {
    transform: translateY(0);
    opacity: 1;
  }
}

.digit.animate {
  animation-name: floatUpDisappear;
  animation-duration: 0.4s;
  animation-fill-mode: forwards;
  animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

.digit:not(.animate) {
  animation-name: floatUpAppear;
  animation-duration: 0.4s;
  animation-fill-mode: forwards;
  animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}
</style>
